
/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent () {
  const event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}

export function handleScrollHeader (callback) {
  let timer = 0

  let beforeScrollTop = window.pageYOffset
  callback = callback || function () {}
  window.addEventListener(
    'scroll',
    event => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        let direction = 'up'
        const afterScrollTop = window.pageYOffset
        const delta = afterScrollTop - beforeScrollTop
        if (delta === 0) {
          return false
        }
        direction = delta > 0 ? 'down' : 'up'
        callback(direction)
        beforeScrollTop = afterScrollTop
      }, 50)
    },
    false
  )
}

export function isIE () {
  const bw = window.navigator.userAgent
  const compare = (s) => bw.indexOf(s) >= 0
  const ie11 = (() => 'ActiveXObject' in window)()
  return compare('MSIE') || ie11
}

/**
 * 
 * @param {判断是否为JSON} str 
 */
export function isJSON(str) {
  if (typeof str == 'string') {
      try {
          var obj=JSON.parse(str);
          if(typeof obj == 'object' && obj ){
              return true
          }else{
              return false
          }

      } catch(e) {
          return false
      }
  }else if (typeof str == 'object'  && str) {
    return true
  }
 
}
/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate (id = '', timeout = 1500) {
  if (id === '') {
    return
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id))
  }, timeout)
}

/**
 * 由一个组件，向下找到最近的指定组件，根据组件名
 * @param {父组件} context 
 * @param {ref} ref 
 */
export function findComponentDownwardByRef (context, ref) {
    const childrens = context.$children;
    let children = null;
  
    if (childrens.length) {
            for (const child of childrens) {
                if(ref in child.$refs){
                    children = child;
                    break
            } else {
                children = findComponentDownwardByRef(child, ref);
                if (children) break;
            }
        }
    }
    return children;
  }


/**
 * 由一个组件，向下找到最近的指定组件，根据组件名
 * @param {父组件} context 
 * @param {组件名} componentName 
 */
export function findComponentDownward (context, componentName) {
  const childrens = context.$children;
  let children = null;

  if (childrens.length) {
    for (const child of childrens) {
      const name = child.$options.name;

      if (name === componentName) {
        children = child;
        break;
      } else {
        children = findComponentDownward(child, componentName);
        if (children) break;
      }
    }
  }
  return children;
}

/**
 * 由一个组件，向下找到所有指定的组件，根据组件名
 * @param {父组件} context 
 * @param {组件名} componentName 
 */
export function findComponentsDownward (context, componentName) {
  return context.$children.reduce((components, child) => {
    if (child.$options.name === componentName) components.push(child);
    const foundChilds = findComponentsDownward(child, componentName);
    return components.concat(foundChilds);
  }, []);
}

/**
 * 由一个组件，向上找到最近的指定组件,根据组件名
 * @param {组件} context 
 * @param {组件名} componentName 
 */
export function findComponentUpward (context, componentName) {
  let parent = context.$parent;
  let name = parent.$options.name;
  while (parent && (!name || [componentName].indexOf(name) < 0)) {
    parent = parent.$parent;
    if (parent) name = parent.$options.name;
  }
  return parent;
}
  /**
   * 由一个组件，向上找到所有的指定组件,根据组件名
   * @param {组件} context 
   * @param {组件名} componentName 
   */
export function findComponentsUpward (context, componentName) {
  let parents = [];
  const parent = context.$parent;

  if (parent) {
    if (parent.$options.name === componentName) parents.push(parent);
    return parents.concat(findComponentsUpward(parent, componentName));
  } else {
    return [];
  }
}

/**
 * 下拉
 * @param {*} dictOptions 
 * @param {itemValue:'',itemText:''} replaceFields 转换的字段
 * @param {*} val 
 */
export function filterDictText(dictOptions,val) {
  if(!val || !dictOptions || dictOptions.length==0){
    return ""
  }
  var valArr = val.split(",")
  var res = "";

  for(var i=0;i<valArr.length;i++){
    let reArr = dictOptions.filter(item => item["itemValue"]==valArr[i] || item["value"]==valArr[i])
    if(reArr.length>0){
        res += reArr[0]["itemText"] || reArr[0]["title"];
        res +=","
    }else{
        res +=  filterDictChildText(dictOptions, valArr[i])
        res +=","
    }
  }
  
  return res.slice(0, -1);
}

function filterDictChildText(dictOptions, val){
  let result=val
  for(var i=0;i<dictOptions.length;i++){
    if(dictOptions[i]["value"]==result){
      result = dictOptions[i]["title"]
    }else if(dictOptions[i]["children"]){
      result = filterDictChildText(dictOptions[i]["children"],result)
    }
  }
   return result
}

/**
 * 字符串转JSON
 */
export function StringToJson(str){
    if(typeof(str) == "string" && str.constructor === String && Object.prototype.toString.call(str) == "[object String]" && isJSON(str)){
       return JSON.parse(str)
    }
    return str
}

/**
 * 将指定组件设置自定义名称
 *
 * @param {String} name 组件自定义名称
 * @param {Component | Promise<Component>} component
 * @return {Component}
 */
export function createCustomComponent (name, component) {
   
    return {
      name,
      data () {
        return { component: null }
      },
      async created () {
        if (component instanceof Promise) {
          try {
            const module = await component
            this.component = module?.default
          } catch (error) {
            console.error(`无法解析组件 ${name}, error:`, error)
          }
  
          return
        }
        this.component = component
      },
      render (h) {
        return this.component ? h(this.component) : null
      },
    }
}


export function createExtPage (name, extLink) {
   
    return {
      name,
      data () {
        return { extLink: null,width:1000,height:600 }
      },
      async created () {
        this.extLink = extLink
        this.width=document.documentElement.clientWidth-220;
        this.height=document.documentElement.clientHeight-100;
       
      },
      render (h) {
        return h('iframe',{attrs: {
            src: this.extLink,
            width:this.width,
            height:this.height,
            frameborder: 0,
            scrolling: 'no',
            allowfullscreen: true
          }})
      },
    }
}
